package com.example.remindme.RemindModule.DataCard.Fragment

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.remindme.R
import com.example.remindme.RemindDatabase.MatterEntity
import com.example.remindme.RemindModule.DataCard.ViewHolder.ClickData
import com.example.remindme.RemindModule.DataCard.ViewHolder.Matter
import com.example.remindme.RemindModule.DataCard.ViewHolder.RecyclerData
import com.example.remindme.RemindModule.DataCard.ViewHolder.ViewAdapter
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.*
import kotlin.collections.ArrayList


val TYPE_TODAY="today"
val TYPE_ALL="all"
val TYPE_SCHEDULED="scheduled"
val TYPE_FALGGED="flagged"


class taskFragment : Fragment() {

    companion object {
        fun newInstance() = taskFragment()
    }

    lateinit var listName:TextView
    lateinit var taskRecyView:RecyclerView
    lateinit var viewModel: TaskViewModel
    lateinit var myadapter:ViewAdapter
     var data=ArrayList<RecyclerData>()

    var tempDataToday=ArrayList<RecyclerData>()
    var tempDataAll=ArrayList<RecyclerData>()
    var tempDataScheduled=ArrayList<RecyclerData>()
    var tempDataFlag=ArrayList<RecyclerData>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.task_fragment, container, false)
    }
    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
    }


    override fun onStart() {

        viewModel.listType.observe(this,{
            Log.d("observe","i changed to :$it")
            addObserverMatters(it)
            listName.text=it
            //searchAll(it)
        })
        super.onStart()
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
     // 从控件中找到recyclerview
           taskRecyView= view!!.findViewById(R.id.taskRecycler)
        listName=view!!.findViewById(R.id.listName_task)
        Log.d("life","taskFragment Created")
        myadapter= ViewAdapter(data)


    }


    fun addObserverMatters(type:String)
    {
        GlobalScope.launch {
            viewModel.queryRoomByTimed()  // 这个函数查询到的 是有时间标记的，today和scheduled 从这里查找
        }
        GlobalScope.launch {
            viewModel.queryRoom()
        }
        GlobalScope.launch {
            viewModel.queryRoomByTimed()
        }
        GlobalScope.launch {
            viewModel.queryRoomFlagged()
        }


        // 对每个数据建立不同的监听，需要的时候直接加载数据
        viewModel.getAllData()?.observe(this,  {
            tempDataAll.clear()
            it.forEach{
                val a= Matter(it.id,it.matterType,it.matter,it.isFlag==1,it.timed)
                Log.d("search",a.toString())
                // isFlag==1,说明有旗标
                tempDataAll.add(a)
            }
            SetAdapter(type)
            // 利用viewmodel 与livedata room相结合
            // viewmodel 加载数据库，当数据库内容发生变化，立即更新
        })

        viewModel.getFlagData()?.observe(this,  {
            tempDataFlag.clear()
            // 先把数据清空
            it.forEach{
                val a= Matter(it.id,it.matterType,it.matter,it.isFlag==1,it.timed)
                Log.d("search",a.toString())
                // isFlag==1,说明有旗标
                tempDataFlag.add(a)
            }
            SetAdapter(type)
        })

        viewModel.getScheduleData()?.observe(this,  {
            tempDataScheduled.clear()
            // 先把数据清空
            it.forEach{
                val a= Matter(it.id,it.matterType,it.matter,it.isFlag==1,it.timed)
                Log.d("search",a.toString())
                // isFlag==1,说明有旗标
                tempDataScheduled.add(a)
            }
            SetAdapter(type)
        })

        viewModel.getTodayData()?.observe(this,  {
            tempDataToday.clear()
            // 先把数据清空
            val cal=Calendar.getInstance()
            it.forEach{
                val date=Date(it.timed)
                val dataCal= Calendar.getInstance()
                dataCal.time=date
                // 判断存储的时间是不是一天
                if(cal.get(Calendar.DAY_OF_YEAR)==dataCal.get(Calendar.DAY_OF_YEAR)
                    && cal.get(Calendar.YEAR)==dataCal.get(Calendar.YEAR))
                {
                    val a= Matter(it.id,it.matterType,it.matter,it.isFlag==1,it.timed)
                    Log.d("search",a.toString())
                    tempDataToday.add(a)
                }
            }
            SetAdapter(type)
        })



        if(type!= TYPE_TODAY &&type!= TYPE_FALGGED &&type!= TYPE_SCHEDULED &&type!= TYPE_ALL)
        {
            data.clear()
            Log.d("inAll", "----------------------------------in all------------------")
            myadapter= ViewAdapter(data)
            GlobalScope.launch {
                viewModel.queryRoomByType(type)  //todo refactor this era
            }
            initViewHolder()
            // 利用viewmodel 与livedata room相结合
            // viewmodel 加载数据库，当数据库内容发生变化，立即更新
            viewModel.getData()?.observe(this,  {

                // 先把数据清空
                it.forEach{
                    val a= Matter(it.id,it.matterType,it.matter,it.isFlag==1,it.timed)
                    Log.d("search",a.toString())
                    // isFlag==1,说明有旗标
                    data.add(a)

                }
                myadapter.notifyDataSetChanged()
            })
        }
    }

    private fun SetAdapter(type: String) {
        if(type== TYPE_ALL){
            Log.d("inAll", "----------------------------------in all------------------")
            // myadapter= ViewAdapter(data)
            data=tempDataAll
            myadapter= ViewAdapter(data)
            myadapter.notifyDataSetChanged()
            initViewHolder()
        }
        else if(type== TYPE_SCHEDULED)
        {

            Log.d("inSCH", "----------------------------------in scheduled------------------")
            data=tempDataScheduled
            myadapter= ViewAdapter(data)
            myadapter.notifyDataSetChanged()
            initViewHolder()

        }
        else if(type== TYPE_FALGGED)
        {

            Log.d("in flag", "----------------------------------in flag------------------")
            data=tempDataFlag
            myadapter= ViewAdapter(data)
            myadapter.notifyDataSetChanged()
            initViewHolder()
        }
        else if(type== TYPE_TODAY)
        {
            Log.d("in today", "----------------------------------in today------------------")
            data=tempDataToday
            myadapter= ViewAdapter(data)
            myadapter.notifyDataSetChanged()
            initViewHolder()
        }
    }
    private fun initViewHolder() {
        taskRecyView.layoutManager= LinearLayoutManager(activity)
       // val adapter= ViewAdapter(data)  // adapeter 会在内部完成
        taskRecyView.adapter=myadapter
        taskRecyView.setHasFixedSize(true)
        // 匿名对象
        myadapter.setOnItemClick(object: ViewAdapter.onRecyclerViewItemClickListener {
            // 对按钮设置点击响应事件
            override fun onItemClick(view: View, position: Int) {
                if(viewModel.current!=null)
                {
                    viewModel.current!!.layout.setBackgroundColor(resources.getColor(R.color.white))
                }
                val linecons=view.findViewById<ConstraintLayout>(R.id.line_cons)
                val blockcons=view.findViewById<ConstraintLayout>(R.id.blockCons)
                val listcons=view.findViewById<ConstraintLayout>(R.id.listCons)

                val blockRadio=view.findViewById<RadioButton>(R.id.timeradio)

                val temp=data[position] as Matter
               val isFalg= when(temp.isFlag){
                   true->1
                   false->0}
                val entity=MatterEntity(temp.id,temp.listType,temp.matter,isFalg,temp.timed)
                if(linecons!=null)
                {   val lineRadio=view.findViewById<RadioButton>(R.id.ComRadio)
                    if(lineRadio!=null)
                    {
                        lineRadio.isEnabled=true
                        if(lineRadio.isChecked)
                        {
                            GlobalScope.launch {

                                viewModel.deleteFromRoom(entity)
                            }
                            addObserverMatters(viewModel.listType.value!!)

                        }
                    }
                    linecons.setBackgroundColor(resources.getColor(R.color.click))
                    viewModel.current= ClickData(linecons,true)
                }
                else if(blockcons!=null){
                    val blockRadio=view.findViewById<RadioButton>(R.id.timeradio)
                    if(blockRadio!=null)
                    {
                        blockRadio.isEnabled=true
                        if(blockRadio.isChecked)
                        {
                            GlobalScope.launch {

                                viewModel.deleteFromRoom(entity)
                            }
                            addObserverMatters(viewModel.listType.value!!)

                        }
                    }
                    blockcons.setBackgroundColor(resources.getColor(R.color.click))
                    viewModel.current=ClickData(blockcons,true)
                }
                else if (listcons!=null)
                {
                    listcons.setBackgroundColor(resources.getColor(R.color.purple_200))
                    viewModel.current=ClickData(listcons,true)
                }

            }
        })
    }

}